package com.caijinbang.study.controller;

import com.caijinbang.study.entity.DemoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Locale;

/**
 * 验证测试控制类
 *
 * @author caijb
 * @version 1.0.0
 * @date 2018-04-25 22:06
 */
@RestController
public class ValidateController {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = "/validator", method = RequestMethod.GET)
    public String validate(@Valid DemoEntity demoEntity, BindingResult result) {

        if (result.hasErrors()) {
            StringBuffer msg = new StringBuffer();
            //获取错误字段集合
            List<FieldError> fieldErrors = result.getFieldErrors();
            //获取本地址LOCAL,zh_CN
            Locale currentLocale = LocaleContextHolder.getLocale();
            //遍历错误字段,获取错误信息
            fieldErrors.forEach(fieldError -> {
                String errorMessage = messageSource.getMessage(fieldError, currentLocale);
                msg.append(fieldError.getField() + ":" + errorMessage + ",");
            });
            return msg.toString();
        }
        return demoEntity.toString();
    }
}
